<!-- 文件切片上传 -->
<template>
  <div>
    <el-upload class="mine-slice-upload" :on-change="fileListChange" :multiple="false" action="" :http-request="mineUploadMethods" drag :accept="fileType" :file-list="fileList" ref="sliceUpload">
      <i class="icon-upload-line iconfont"></i>
      <div class="el-upload__text"><b>点击或拖拽文件到此区域以上传</b></div>
      <div class="el-upload__text file-limit">
        <span>支持拓展名：</span>
        <span>{{ fileType.replace(/\,/g, ' ') }}</span>
      </div>
    </el-upload>
    <el-dialog class="progress-dialog" :close-on-click-modal="false" :visible.sync="uploadProcessDialogShow" width="450px" :showClose="false">
      <div class="percent-info">
          <i class="el-icon-warning-outline icon"></i>
          <span class="percent-info-word">上传文件</span>
        </div>
      <!-- <el-progress class="margin-bottom-20" :text-inside="true" :stroke-width="15" :percentage="uploadPercent"></el-progress> -->
      <el-progress class="margin-bottom-20" :stroke-width="13" :percentage="uploadPercent"></el-progress>
    </el-dialog>
  </div>
</template>

<script>
export default {

  props: {
    fileType: { // 上传文件类型
      type: String,
      required: false,
      default: "",
    }
  },

  data () {
    return {
      fileList: [], // 已经上传文件列表
      uploadProcessDialogShow: false, // 是否显示上传进度对话框
      uploadPercent: 0, // 上传进度条
    }
  },

  methods: {

    // 自定义的上传方法
    mineUploadMethods (data) {
      if (this.check(data.file.name)) {
        this.$message({ type: "error", message: "文件名中不能存在特殊符号" });
        return;
      }
      var file = data.file;
      this.uploadPercent = 0;
      this.uploadProcessDialogShow = true;
      this.getServerFileInfo(file);
    },

    // 检查文件名存在特殊字符
    check (str) {
      var pattern = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\]<>《》/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？ ]");
      if (pattern.test(str)) {
        return true;
      }
      return false;
    },

    // 文件发生改变
    fileListChange: function (file, fileList) {
      if (file.name.indexOf(" ") != -1) {
        this.fileList = [];
        return;
      }
			if (fileList.length) {
				fileList = [fileList[fileList.length - 1]];
			} else {
				fileList = [];
			}
			this.uploadStatus = "waiting";
			this.fileList = fileList;
			this.$emit("change", { file: file, fileList: fileList });
		},

    // 获取文件在服务器的断点
    async getServerFileInfo (fileData) {
      var formData = new FormData();
      formData.append("fileName", fileData.name);
      try {
        const res = await this.$store.dispatch('aiUploadGetUploadId', formData);
        const result = res.data || {};
        if (result.success) {
          const resultData = result.data || {};
          this.sliceFile(fileData, resultData);
        }
      } catch (error) {
        console.log(error);
      }
    },

    // 文件切片并筛选要上传的切片
    async sliceFile (file, serverFileData) {
      var exist = serverFileData.parts || [];
      const fileSplitSize = 3 * 1024 * 1024;
      const fileSplitTimes = Math.ceil(file.size / fileSplitSize);
      for (var i = 0; i < fileSplitTimes; i++) {
        var partNumber = i + 1;
        if (exist.indexOf(partNumber) == -1) {
          this.uploadPercent = (100 * partNumber / (fileSplitTimes + 1));
          const sliceFile = file.slice(i * fileSplitSize, (i + 1) * fileSplitSize);
          const formData = new FormData;
          formData.append("file", sliceFile);
          formData.append("partNumber", partNumber);
          formData.append("certName", serverFileData.certName);
          formData.append("uploadId", serverFileData.uploadId);
          formData.append("fileNameOSS", serverFileData.fileNameOSS);
          await this.uploadFile(formData);
        }
      }
      this.getFileSliceList(serverFileData);
    },

    // 上传文件
    async uploadFile (uploadData) {
      try {
        await this.$store.dispatch('aiUploadUploadParts', uploadData);
      } catch (error) {
        console.log(error);
      }
    },

    // 获取上传的文件切片列表
    async getFileSliceList (serverFileData) {
      const send = {
        certName: serverFileData.certName,
        uploadId: serverFileData.uploadId,
        fileName: serverFileData.fileName,
        fileNameOSS: serverFileData.fileNameOSS
      }
      try {
        const res = await this.$store.dispatch('aUuploadGetUploadList', send);
        const result = res.data || {};
        if (result.success) {
          const resultData = result.data || {};
          this.fileSynthesis(resultData);
        } else {
          this.$message({ type: "error", message: "上传文件失败" });
        }
      } catch (error) {
        console.log(error);
      }
    },

    // 合成文件
    async fileSynthesis (send) { 
      try {
        const res = await this.$store.dispatch('aiUploadGetUploadComplete', send);
        const result = res.data || {};
        if (result.success) {
          this.uploadPercent = 100;
          // this.$message({ type: "success", message: result.msg });
          this.$emit("uploadSuccess", send);
        } else {
          this.$message({ type: "success", message: "上传失败" });
        }
        this.uploadProcessDialogShow = false;
        this.$emit("refreshImportFile");
      } catch (error) {
        console.log(error);
      }
    }

  }

}
</script>

<style lang="less" scoped>
.mine-slice-upload {
  width: 400px;
}

.progress-dialog /deep/ .el-dialog__header {
  border-bottom: none;
}

.progress-dialog /deep/ .el-dialog__header {
  padding: 2px;
}

.progress-dialog {
  padding-bottom: 20px;
}

.percent-info {
  width: 304px;
  height: 24px;
  font-family: PingFangSC-Medium;
  font-size: 16px;
  color: rgba(0,0,0,0.85);
  line-height: 24px;
  font-weight: 500;
  margin-bottom: 20px;
  padding-left: 10px;
  margin-bottom: 20px;
}

.margin-bottom-20 {
  margin-bottom: 20px;
}

/deep/ .el-progress__text {
  font-size: 15px !important;
}

.icon {
  font-weight: 600;
  margin-right: 10px;
  color: #0b8cd7;
}

</style>
